package com.zbkj.crmeb.merchant.admin.service.impl;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.utils.*;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.response.PickingProductResponse;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.export.vo.*;
import com.zbkj.crmeb.image.model.ProductImage;
import com.zbkj.crmeb.image.service.ProductImageService;
import com.zbkj.crmeb.merchant.admin.service.MerInsertUserService;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.request.StoreProductAttrValueRequest;
import com.zbkj.crmeb.store.request.StoreProductCrmebRequest;
import com.zbkj.crmeb.store.response.PriceResult;
import com.zbkj.crmeb.store.response.SupplierInfo;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.system.service.SystemCountryService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.zbkj.crmeb.category.model.Category;
import com.zbkj.crmeb.category.service.CategoryService;
import com.zbkj.crmeb.export.service.ExcelService;
import com.zbkj.crmeb.merchant.admin.service.MerExcelService;
import com.zbkj.crmeb.store.request.StoreProductSearchRequest;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.upload.service.AsyncService;
import org.springframework.web.multipart.MultipartFile;

/**
* @author Mr.Zhang
* @Description ExcelServiceImpl 接口实现
* @since 2020-05-06
*/
@Service
public class MerExcelServiceImpl implements MerExcelService {

    @Autowired
    private StoreProductService storeProductService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private StoreProductRelationService storeProductRelationService;

    @Autowired
    private StoreBrandService storeBrandService;

    @Autowired
    AsyncService asyncService;
    @Autowired
    private MarkupRateService markupRateService;

    @Autowired
    private ExcelService excelService;
    @Autowired
    private PriceUtil priceUtil;
    @Autowired
    private MerInsertUserService merInsertUserService;
    @Autowired
    private ChannelUserUploadService channelUserUploadService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private ICategoryMatchService categoryMatchService;
    @Autowired
    private StoreProductDraftService storeProductDraftService;
    @Autowired
    private StoreProductAttrValueDraftService storeProductAttrValueDraftService;
    @Autowired
    private StoreProductUploadService storeProductUploadService;
    @Autowired
    private ProductImageService productImageService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private SystemCountryService systemCountryService;

    @Value("${aliyun.oss.oss-url}")
    private String ossUrl;

    /**
     * 商品列表导出
     * @param request 请求参数
     * @author Mr.Zhang
     * @since 2020-05-06
     */
    @Override
    public List<ProductExcelVo> product(StoreProductSearchRequest request) {
        PageParamRequest pageParamRequest = new PageParamRequest();
        pageParamRequest.setPage(Constants.DEFAULT_PAGE);
        pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
        PageInfo<StoreProductResponse> storeProductResponsePageInfo = storeProductService.getList(request, pageParamRequest);
        List<StoreProductResponse> list = storeProductResponsePageInfo.getList();
        if(list.size() < 1){
            throw new CrmebException("没有可导出的数据！");
        }

        //从集合中取出ID
        List<Integer> idList = list.stream().map(StoreProductResponse::getId).distinct().collect(Collectors.toList());

        //产品分类id
        List<Integer> cateIdListStr = list.stream().map(StoreProductResponse::getCateId).distinct().collect(Collectors.toList());

        HashMap<Integer, String> categoryNameList = new HashMap<Integer, String>();
        if(cateIdListStr.size() > 0){
            String join = StringUtils.join(cateIdListStr, ",");
            List<Integer> cateIdList = CrmebUtil.stringToArray(join);
            categoryNameList = categoryService.getListInId(cateIdList);
        }

        //点赞
        HashMap<Integer, Integer> likeCount = storeProductRelationService.getLikeCountListInProductId(idList);

        //收藏
        HashMap<Integer, Integer> collectCount = storeProductRelationService.getCollectCountListInProductId(idList);

        ArrayList<ProductExcelVo> productExcelVoList = new ArrayList<>();
        for (StoreProductResponse storeProductResponse : list ) {
//            productExcelVoList.add(
//                    new ProductExcelVo(
//                            storeProductResponse.getStoreName(),
//                            storeProductResponse.getStoreInfo(),
//                            CrmebUtil.getValueByIndex(categoryNameList, storeProductResponse.getCateId()),
//                            storeProductResponse.getPrice(),
//                            storeProductResponse.getSales(),
//                            storeProductResponse.getStock(),
//                            CrmebUtil.getIntValueByIndex(likeCount, storeProductResponse.getId()),
//                            CrmebUtil.getIntValueByIndex(collectCount, storeProductResponse.getId())
//                    )
//            );
        }
        return productExcelVoList;
    }

    @Override
    public void parseList(List<ProductExcelVo> list) {
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        // 处理category数据
        List<Category> categorys = categoryService.list();
        Map<Integer, Category> categoryMap = categorys.stream().collect(Collectors.toMap(Category :: getId, s -> s));

        for (ProductExcelVo excelVo : list) {
            // 商品标签处理
            List<Integer> productCateIds = Collections.singletonList(excelVo.getCateId());
            StringBuilder sb = new StringBuilder();
            for(int i=0; i<productCateIds.size(); i++) {
                Category category = categoryMap.get(productCateIds.get(i));
                sb.append(null == category ? "" : category.getName());
                if(i <productCateIds.size()-1) {
                    sb.append(",");
                }
            }
            if (Objects.nonNull(excelVo.getAddTime())) {
                excelVo.setCreateTime(DateUtil.dateToStr(new Date(excelVo.getAddTime() * 1000L),Constants.DATE_FORMAT));
            }
            excelVo.setCateName(sb.toString());
            // 图片压缩
            String imgUrl = excelVo.getImage();
            imgUrl = StringUtil.isEmpty(imgUrl) ? "" : imgUrl.substring(0, -1 == imgUrl.indexOf("?") ? imgUrl.length() : imgUrl.indexOf("?"))+"?x-oss-process=image/resize,m_fill,w_100,h_100";
            excelVo.setImage(imgUrl);
            }
        }

    @Override
    public List<MerFlowExcelVo> getMerFlowList(Integer merId, Integer type, PageParamRequest request) {
        return excelService.getMerFlowList(merId,type,request);
    }

    @Override
    public List<MerFlowExcelVo> getAgentFlowExport(Integer agentId, Integer type, PageParamRequest request) {
        return excelService.getAgentFlowList(agentId,type,request);
    }

    @Override
    public List<PickingProductExcelVo> parsePickingVoList(List<PickingProductResponse> responseList) {
        List<PickingProductExcelVo> list = new ArrayList<>();
        for (PickingProductResponse productResponse : responseList) {
            PickingProductExcelVo vo = new PickingProductExcelVo();
            BeanUtils.copyProperties(productResponse,vo);
            vo.setTempName(StockAreaTempEnum.getByTempId(productResponse.getTempId()).getStockAreaName());
            vo.setPriceEur(priceUtil.rmb2EurStatic(productResponse.getPrice(), productResponse.getExchangeRate()));
            vo.setCostEur(priceUtil.rmb2EurStatic(productResponse.getCost(), productResponse.getExchangeRate()));
            vo.setWholesalePriceEur(priceUtil.rmb2EurStatic(productResponse.getWholesalePrice(), productResponse.getExchangeRate()));
            vo.setOtPriceRmb(priceUtil.eur2RmbStatic(productResponse.getOtPrice(), productResponse.getExchangeRate()));
            // 图片压缩
            String imgUrl = productResponse.getImage();
            imgUrl = StringUtil.isEmpty(imgUrl) ? "" : imgUrl.substring(0, !imgUrl.contains("?") ? imgUrl.length() : imgUrl.indexOf("?"))+"?x-oss-process=image/resize,m_fill,w_100,h_100";
            vo.setImage(imgUrl);
            list.add(vo);
        }
        return list;
    }

    @Override
    public List<FrontPickingProductExcelVo> parseFrontPickingVoList(List<PickingProductResponse> responseList) {
        List<FrontPickingProductExcelVo> list = new ArrayList<>();
        for (PickingProductResponse productResponse : responseList) {
            FrontPickingProductExcelVo vo = new FrontPickingProductExcelVo();
            BeanUtils.copyProperties(productResponse,vo);
            vo.setTempName(StockAreaTempEnum.getByTempId(productResponse.getTempId()).getStockAreaName());
            // 图片压缩
            String imgUrl = productResponse.getImage();
            imgUrl = StringUtil.isEmpty(imgUrl) ? "" : imgUrl.substring(0, !imgUrl.contains("?") ? imgUrl.length() : imgUrl.indexOf("?"))+"?x-oss-process=image/resize,m_fill,w_100,h_100";
            vo.setImage(imgUrl);
            list.add(vo);
        }
        return list;
    }

    @Override
    public String uploadExcel(MultipartFile file, Integer merId) {
        try {
            if (StringUtils.isBlank(file.getOriginalFilename())){
                throw new CrmebException("文件名不能为空");
            }
            String excelType = OSSUtil.getExcelType(FilenameUtils.getExtension("." + file.getOriginalFilename()));
            if (StringUtils.isEmpty(excelType)){
                throw new CrmebException("文件格式不合法，必须为csv,xls,xlsx");
            }
            long start = System.currentTimeMillis();
            InputStream inputStream = file.getInputStream();
            List<UploadUserExcelVo> list = ExcelUtil.importExcel(inputStream, UploadUserExcelVo.class);
            ChannelUserUpload channelUserUpload = merInsertUserService.importUserList(list, merId);
            String fileName = file.getOriginalFilename();
            if (fileName.contains("-")){
                fileName = fileName.substring(fileName.lastIndexOf("-") + 1);
            }
            String url = OSSUtil.uploadLocalExcel(Constants.UPLOAD_EXCEL_FILE_WAREHOUSE_DIR, file, start + "-" + fileName);
            channelUserUpload.setTime(System.currentTimeMillis() - start);
            channelUserUpload.setUrl(url);
            channelUserUpload.setResult(StringUtils.isBlank(url) ? 0 : 1);
            channelUserUploadService.save(channelUserUpload);
            return channelUserUpload.getMsg();
        } catch (Exception e){
            e.printStackTrace();
            throw new CrmebException(e.getMessage());
        }
    }

    /**
     * 功能描述: 导入商品
     * @Param: [list, merId]
     * @Return: com.zbkj.crmeb.store.model.StoreProductUpload
     * @Author: wangzh
     * @Date: 2022/12/22 15:27
     */
    @Override
    public StoreProductUpload  importProductList(List<UploadSupplierProductExcelVo> list, Integer merId) {
        //获取供应商信息
        SupplierInfo supplierInfo = new SupplierInfo();
        Supplier supplier = supplierService.getSupplierBarcode(merId);
        BeanUtils.copyProperties(supplier, supplierInfo);
        supplierInfo.setSupplierId(supplier.getId());
        supplierInfo.setSupplierName(supplier.getSuppliersName());
        //导入商品总数
        int total = list.size();
        //导入商品所有分类id
        List<Integer> cateIdList = list.stream().map(UploadSupplierProductExcelVo::getCateId).distinct().collect(Collectors.toList());
        cateIdList.removeIf(Objects::isNull);
        //获取系统存在的分类id
        List<Integer> cateList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(cateIdList)){
            cateList = categoryMatchService.list(Wrappers.<CategoryMatch>lambdaQuery().eq(CategoryMatch::getType, 1).in(CategoryMatch::getId,cateIdList)
                    .select(CategoryMatch::getId)).stream().map(CategoryMatch::getId).collect(Collectors.toList());
        }
        //导入商品品牌id
        List<Integer> brandIdList = list.stream().map(UploadSupplierProductExcelVo::getBrandId).distinct().collect(Collectors.toList());
        brandIdList.removeIf(Objects::isNull);
        //品牌id与名称映射关系
        Map<Integer,String> brandMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(brandIdList)){
            brandMap = storeBrandService.list(Wrappers.<StoreBrand>lambdaQuery().eq(StoreBrand::getType, 1).in(StoreBrand::getId,brandIdList)
                    .select(StoreBrand::getId,StoreBrand::getEnName)).stream().collect(Collectors.toMap(StoreBrand::getId,StoreBrand::getEnName));
        }
        //发货地id
        List<Integer> tempIdList = Arrays.stream(StockAreaTempEnum.values()).map(StockAreaTempEnum::getTempId).collect(Collectors.toList());
        Set<UploadSupplierProductExcelVo> draftProductSet = new HashSet<>();
        //失败数量
        int sum = groupProductList(list, cateList, brandMap, tempIdList, draftProductSet);
        //上传商品去除草稿箱中的商品
        list.removeAll(draftProductSet);
        //根据国际编码进行分组，得到map
        Map<String, List<UploadSupplierProductExcelVo>> productMap = list.stream().collect(Collectors.groupingBy(UploadSupplierProductExcelVo::getKeyword));
        //正常商品
        for (Map.Entry<String, List<UploadSupplierProductExcelVo>> productListEntry : productMap.entrySet()) {
            List<UploadSupplierProductExcelVo> productList = productListEntry.getValue();
            //同一个国际编码的商品根据发货地分组
            Map<Integer, List<UploadSupplierProductExcelVo>> tempMap = productList.stream().collect(Collectors.groupingBy(UploadSupplierProductExcelVo::getTempId));
            for (Map.Entry<Integer, List<UploadSupplierProductExcelVo>> tempEntry : tempMap.entrySet()) {
                List<UploadSupplierProductExcelVo> tempList = tempEntry.getValue();
                //去除色号为空的商品，并通过色号分组
                Map<String, List<UploadSupplierProductExcelVo>> colorMap = tempList.stream().filter(item-> StringUtils.isNotBlank(item.getColorCode())).collect(Collectors.groupingBy(UploadSupplierProductExcelVo::getColorCode));
                //色号为空的商品集合
                List<UploadSupplierProductExcelVo> productExcelVoList = tempList.stream().filter(item -> StringUtils.isBlank(item.getColorCode())).collect(Collectors.toList());
                //存在色号为空的商品，存入map中
                if(CollectionUtils.isNotEmpty(productExcelVoList)){
                    colorMap.put(null,productExcelVoList);
                }
                for (Map.Entry<String, List<UploadSupplierProductExcelVo>> colorEntry : colorMap.entrySet()) {
                    List<UploadSupplierProductExcelVo> colorList = colorEntry.getValue();
                    //尺码与商品信息映射关系
                    Map<String, UploadSupplierProductExcelVo> map = colorList.stream().collect(Collectors.toMap(UploadSupplierProductExcelVo::getSkuSize, e -> e,(value1, value2) -> value2));
                    List<UploadSupplierProductExcelVo> sizeList = new ArrayList<>(map.values());
                    //计算商品总库存
                    int stock = sizeList.stream().mapToInt(UploadSupplierProductExcelVo::getAttrStock).sum();
                    StoreProductCrmebRequest storeProductCrmebRequest = this.buildImportProduct(sizeList, tempEntry.getKey(),colorEntry.getKey(),supplierInfo, merId);
                    //通过barcode获取是否有该商品
                    StoreProduct storeProduct = storeProductService.getByBarCode(storeProductCrmebRequest.getBarCode());
                    if(storeProduct != null && !Objects.equals(storeProduct.getCommodityType(),2)){
                        continue;
                    }
                    //没有该商品，保存该商品，或者商品类型为2
                    storeProductService.saveOtProduct(storeProductCrmebRequest, storeProduct, stock, merId);
                }
            }
        }
        //异常商品（加入草稿箱）
        Map<String, List<UploadSupplierProductExcelVo>> draftProductMap = draftProductSet.stream().collect(Collectors.groupingBy(UploadSupplierProductExcelVo::getKeyword));
        //异常商品（加入草稿箱）
        for (Map.Entry<String, List<UploadSupplierProductExcelVo>> draftProductEntry : draftProductMap.entrySet()) {
            List<UploadSupplierProductExcelVo> draftProductList = draftProductEntry.getValue();
            Map<Integer, List<UploadSupplierProductExcelVo>> draftTempMap = draftProductList.stream().collect(Collectors.groupingBy(UploadSupplierProductExcelVo::getTempId));
            for (Map.Entry<Integer, List<UploadSupplierProductExcelVo>> draftTempEntry : draftTempMap.entrySet()) {
                List<UploadSupplierProductExcelVo> draftTempList = draftTempEntry.getValue();
                Map<String, List<UploadSupplierProductExcelVo>> draftColorMap = draftTempList.stream().filter(item-> StringUtils.isNotBlank(item.getColorCode())).collect(Collectors.groupingBy(UploadSupplierProductExcelVo::getColorCode));
                List<UploadSupplierProductExcelVo> productExcelVoList = draftTempList.stream().filter(item -> StringUtils.isBlank(item.getColorCode())).collect(Collectors.toList());
                if(CollectionUtils.isNotEmpty(productExcelVoList)){
                    draftColorMap.put(null,productExcelVoList);
                }
                for (Map.Entry<String, List<UploadSupplierProductExcelVo>> draftColorEntry : draftColorMap.entrySet()) {
                    Map<String, UploadSupplierProductExcelVo> map = draftColorEntry.getValue().stream().collect(Collectors.toMap(UploadSupplierProductExcelVo::getSkuSize, e -> e,(value1, value2) -> value2));
                    List<UploadSupplierProductExcelVo> sizeList = new ArrayList<>(map.values());
                    //将草稿箱中的商品保存入数据库
                    UploadSupplierProductExcelVo excelVo = sizeList.get(0);
                    // barcode
                    String barCode = supplierInfo.getBarcode() + excelVo.getKeyword() + "-" + draftTempEntry.getKey()+ "-" + draftColorEntry.getKey();
                    StoreProductDraft exitStoreProductDraft = storeProductDraftService.getOne(Wrappers.<StoreProductDraft>lambdaQuery().eq(StoreProductDraft::getBarCode, barCode));
                    StoreProductDraft storeProductDraft = new StoreProductDraft();;
                    if(exitStoreProductDraft != null){
                        storeProductDraft = exitStoreProductDraft;
                    }
                    BeanUtils.copyProperties(excelVo,storeProductDraft,"sliderImage");
                    BigDecimal cost = sizeList.stream().filter(e -> e.getCost() != null && e.getCost().compareTo(BigDecimal.ZERO) > -1).map(UploadSupplierProductExcelVo::getCost).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
                    PriceResult priceResult = priceUtil.eur2Rmb(cost);
                    BigDecimal otPrice = sizeList.stream().filter(e -> e.getOtPrice() != null && e.getOtPrice().compareTo(BigDecimal.ZERO) > -1).map(UploadSupplierProductExcelVo::getOtPrice).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
                    List<String> collect = Stream.of(excelVo.getImage(), excelVo.getImageUrl1(), excelVo.getImageUrl2(), excelVo.getImageUrl3(), excelVo.getImageUrl4(),
                            excelVo.getImageUrl5(), excelVo.getImageUrl6(), excelVo.getImageUrl7(),excelVo.getImageUrl8(), excelVo.getImageUrl9()).collect(Collectors.toList());
                    collect.removeIf(StringUtils::isBlank);
                    JSONArray gallery = JSONArray.parseArray(JSON.toJSONString(collect));
                    if(gallery.size()>0){
                        storeProductDraft.setSliderImage(gallery.toJSONString());
                    }
                    storeProductDraft.setBarCode(barCode);
                    storeProductDraft.setCost(priceResult.getPrice());
                    storeProductDraft.setPrice(priceResult.getPrice());
                    storeProductDraft.setSourceCost(priceResult.getPrice());
                    storeProductDraft.setExchangeRate(priceResult.getExchangeRate());
                    storeProductDraft.setOtPrice(otPrice);
                    storeProductDraft.setCateId(cateList.contains(excelVo.getCateId()) ? excelVo.getCateId().toString() : null);
                    storeProductDraft.setBrandId(brandMap.containsKey(excelVo.getBrandId()) ? excelVo.getBrandId() : null);
                    storeProductDraft.setBrandName(brandMap.get(storeProductDraft.getBrandId()));
                    //供应商信息填充
                    storeProductDraft.setMerId(merId);
                    storeProductDraft.setSuppliersId(supplierInfo.getSupplierId().toString());
                    storeProductDraft.setSuppliersName(supplierInfo.getSupplierName());
                    storeProductDraft.setCountryId(systemCountryService.getIdByName(excelVo.getCountry()));
                    if(storeProductDraft.getId()!=null){
                        storeProductDraftService.updateById(storeProductDraft);
                    }else {
                        storeProductDraftService.save(storeProductDraft);
                    }
                    List<StoreProductAttrValueDraft> valueDraftList = new ArrayList<>();
                    for (UploadSupplierProductExcelVo e : sizeList) {
                        String suk = e.getSkuSize();
                        if(StringUtils.isNotBlank(e.getSkuColor())){
                            suk = e.getSkuColor()+"-"+e.getSkuSize();
                        }
                        StoreProductAttrValueDraft valueDraft = new StoreProductAttrValueDraft();
                        if(exitStoreProductDraft != null){
                            StoreProductAttrValueDraft exitValueDraft = storeProductAttrValueDraftService.getOne(Wrappers.<StoreProductAttrValueDraft>lambdaQuery().eq(StoreProductAttrValueDraft::getProductId, exitStoreProductDraft.getId())
                                    .eq(StoreProductAttrValueDraft::getSuk, suk).select(StoreProductAttrValueDraft::getId));
                            if(exitValueDraft!= null){
                                valueDraft = exitValueDraft;
                            }
                        }
                        valueDraft.setProductId(storeProductDraft.getId());
                        valueDraft.setBarCode(barCode);
                        valueDraft.setStock(e.getAttrStock());
                        valueDraft.setCost(e.getCost()!=null && e.getCost().compareTo(BigDecimal.ZERO)> -1 ? priceUtil.eur2Rmb(e.getCost()).getPrice():null);
                        valueDraft.setPrice(valueDraft.getCost());
                        valueDraft.setSourceCost(valueDraft.getCost());
                        valueDraft.setOtPrice(e.getOtPrice()!=null && e.getOtPrice().compareTo(BigDecimal.ZERO)> -1 ? e.getOtPrice():null);
                        valueDraft.setImage(StringUtils.isNotBlank(e.getSkuImage()) ? e.getSkuImage() : e.getImage());
                        valueDraft.setSuk(suk);
                        valueDraft.setTempId(excelVo.getTempId());
                        LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                        linkedMap.put("尺寸", valueDraft.getSuk());
                        valueDraft.setAttrValue(JSON.toJSONString(linkedMap));
                        valueDraftList.add(valueDraft);
                    }
                    List<StoreProductAttrValueDraft> updateDraftList = valueDraftList.stream().filter(e -> e.getId() != null).collect(Collectors.toList());
                    if(CollectionUtils.isNotEmpty(updateDraftList)){
                        storeProductAttrValueDraftService.updateBatchById(updateDraftList);
                    }
                    valueDraftList.removeAll(updateDraftList);
                    if(CollectionUtils.isNotEmpty(valueDraftList)){
                        storeProductAttrValueDraftService.saveBatch(valueDraftList);
                    }
                }
            }
        }
        String msg = "总计:"+total+",成功:"+list.size()+",草稿箱:"+draftProductSet.size()+",失败:"+sum;
        //添加日志
        StoreProductUpload storeProductUpload = new StoreProductUpload();
        storeProductUpload.setMsg(msg);
        storeProductUpload.setSupplierId(merId);
        storeProductUploadService.save(storeProductUpload);
        return storeProductUpload;
    }

    /**
     * 功能描述: 计算上传失败商品数量，并将某些商品添加入草稿箱
     * @Param: [list, cateList, brandMap, tempIdList, draftProductSet]
     * @Return: int
     * @Author: wangzh
     * @Date: 2022/12/22 15:29
     */
    private int groupProductList(List<UploadSupplierProductExcelVo> list, List<Integer> cateList, Map<Integer, String> brandMap, List<Integer> tempIdList, Set<UploadSupplierProductExcelVo> draftProductSet) {
        int sum = 0;
        Iterator<UploadSupplierProductExcelVo> it = list.iterator();
        //循环上传商品列表
        while(it.hasNext()){
            UploadSupplierProductExcelVo excelVo = it.next();
            //商品国际编码为空，剔除，失败数+1
            if (StringUtils.isBlank(excelVo.getKeyword())) {
                sum++;
                it.remove();
                continue;
            }
            //发货地为空，或者发货地id填写与系统存在的发货地不符，剔除，失败数+1
            if (excelVo.getTempId() == null || !tempIdList.contains(excelVo.getTempId())) {
                sum++;
                it.remove();
                continue;
            }
            //sku尺码未填写，剔除，失败数+1
            if (StringUtils.isBlank(excelVo.getSkuSize())) {
                sum++;
                it.remove();
                continue;
            }
            //商品主图没有填写，存入草稿箱
            if (StringUtils.isBlank(excelVo.getImage())) {
                draftProductSet.add(excelVo);
                continue;
            }
            //商品名称没有填写，存入草稿箱
            if (StringUtils.isBlank(excelVo.getStoreName())) {
                draftProductSet.add(excelVo);
                continue;
            }
            //商品品牌id未填写，或与存在的商品品牌不符，存入草稿箱
            if (null == excelVo.getBrandId() || !brandMap.containsKey(excelVo.getBrandId())) {
                draftProductSet.add(excelVo);
                continue;
            }
            //分类未填写，或与存在的分类不符，存入草稿箱
            if (excelVo.getCateId() == null || !cateList.contains(excelVo.getCateId())) {
                draftProductSet.add(excelVo);
                continue;
            }
            //售价（欧元）未填写，或售价（欧元）小于0，存入草稿箱
            if (excelVo.getCost() == null || excelVo.getCost().compareTo(BigDecimal.ZERO) < 0) {
                draftProductSet.add(excelVo);
                continue;
            }
            //原价（欧元）未填写，或者原价（欧元）小于0，存入草稿箱
            if (excelVo.getOtPrice() == null || excelVo.getOtPrice().compareTo(BigDecimal.ZERO) < 0) {
                draftProductSet.add(excelVo);
                continue;
            }
            //库存未填写，或库存小于0，存入草稿箱
            if (excelVo.getAttrStock() == null || excelVo.getAttrStock() < 0) {
                draftProductSet.add(excelVo);
            }
        }
        return sum;
    }

    /**
     * 商品构建
     * @author daigb
     * @date:  2022-11-09 16:11
     */
    private StoreProductCrmebRequest buildImportProduct(List<UploadSupplierProductExcelVo> list, Integer tempId, String color, SupplierInfo supplierInfo, Integer merId) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = new StoreProductCrmebRequest();
        try {
            UploadSupplierProductExcelVo excelVo = list.get(0);
            List<String> collect = Stream.of(excelVo.getImage(), excelVo.getImageUrl1(), excelVo.getImageUrl2(), excelVo.getImageUrl3(), excelVo.getImageUrl4(),
                    excelVo.getImageUrl5(), excelVo.getImageUrl6(), excelVo.getImageUrl7(),excelVo.getImageUrl8(), excelVo.getImageUrl9()).collect(Collectors.toList());
            collect.removeIf(StringUtils::isBlank);
            JSONArray gallery = JSONArray.parseArray(JSON.toJSONString(collect));
            String mainImage = excelVo.getImage();
            //成本价
            PriceResult priceResult = priceUtil.eur2Rmb(list.stream().map(UploadSupplierProductExcelVo::getCost).min(BigDecimal::compareTo).get());
            BigDecimal cost = priceResult.getPrice();
            //原价
            BigDecimal otPrice = list.stream().map(UploadSupplierProductExcelVo::getOtPrice).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
            StoreBrand storeBrand = storeBrandService.getById(excelVo.getBrandId());
            if(null == storeBrand){
                storeBrand = storeBrandService.getById(5429);
            }
            // barcode
            String barCode = supplierInfo.getBarcode() + excelVo.getKeyword() + "-" + tempId+ "-" + color;
            // 判断供应商自动匹配图片
            boolean isImgMatch = false;
            if(ProductTypeEnum.HOLAWINE.getCode().equals(supplierInfo.getIsEurope())
                    || ProductTypeEnum.XINGFA.getCode().equals(supplierInfo.getIsEurope())
                    || ProductTypeEnum.LICHENG.getCode().equals(supplierInfo.getIsEurope())
                    || ProductTypeEnum.MOBAO.getCode().equals(supplierInfo.getIsEurope())
            ) {
                isImgMatch = true;
            }
            Map<String, String> skuImg = new HashMap<>();
            if(isImgMatch) {
                List<ProductImage> productImages = productImageService.list(Wrappers.<ProductImage>lambdaQuery()
                        .eq(ProductImage :: getFolderName, excelVo.getKeyword())
                        .orderByAsc(ProductImage :: getTypeSort, ProductImage :: getColor, ProductImage :: getSort)
                );
                if(CollectionUtils.isNotEmpty(productImages)) {
                    // 主图替换
                    mainImage = ossUrl + Constants.UPLOAD_FILE_WAREHOUSE_DIR + productImages.get(0).getUrl();
                    gallery = new JSONArray();
                    // 轮播图替换
                    for(ProductImage img : productImages) {
                        skuImg.put(img.getColor(), ossUrl + Constants.UPLOAD_FILE_WAREHOUSE_DIR + img.getUrl());
                        gallery.add(ossUrl + Constants.UPLOAD_FILE_WAREHOUSE_DIR + img.getUrl());
                    }
                }
            }

            List<StoreProductAttr> attrList = new ArrayList<>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<>();
            List<String> sizeValueList = new ArrayList<>();
            // 规格
            StoreProductAttr storeProductAttr = new StoreProductAttr();
            storeProductAttr.setAttrName("尺寸");
            storeProductAttr.setType(0);
            storeProductAttr.setBarCode(barCode);
            for(UploadSupplierProductExcelVo sku : list) {
                BigDecimal erpSkuPrice = priceUtil.eur2Rmb(sku.getCost()).getPrice();
                BigDecimal retailSkuPrice = sku.getOtPrice();
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setSourceSkuId(excelVo.getKeyword() + "-" + tempId+ "-" + color + "-" + sku.getSkuSize());
                storeProductAttrValue.setStock(sku.getAttrStock());
                storeProductAttrValue.setPrice(erpSkuPrice);
                if(isImgMatch) {
                    storeProductAttrValue.setImage(null != skuImg.get(sku.getSkuSize()) ? skuImg.get(sku.getSkuSize()) : mainImage);
                } else {
                    storeProductAttrValue.setImage(StringUtils.isNotBlank(sku.getSkuImage()) ? sku.getSkuImage() : sku.getImage());
                }
                storeProductAttrValue.setCost(erpSkuPrice);
                storeProductAttrValue.setSourceCost(erpSkuPrice);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(retailSkuPrice);
                storeProductAttrValue.setTempId(tempId);
                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                List<String> suk = new ArrayList<>();
                String size = sku.getSkuSize();
                if(StringUtils.isNotBlank(sku.getSkuColor())){
                    size = sku.getSkuColor()+"-"+sku.getSkuSize();
                }
                if(StringUtils.isNotBlank(size)){
                    linkedMap.put("尺寸", size);
                    if(!sizeValueList.contains(size)){
                        sizeValueList.add(size);
                    }
                    suk.add(size);
                }
                //suk
                storeProductAttrValue.setSuk(String.join(",", suk));
                storeProductAttrValue.setAttrValue(linkedMap);
                attrValueList.add(storeProductAttrValue);
            }
            //attr对象
            if (CollectionUtils.isNotEmpty(sizeValueList)) {
                storeProductAttr.setAttrValues(String.join(",", sizeValueList));
                attrList.add(storeProductAttr);
            }
            productRequest.setExchangeRate(priceResult.getExchangeRate());
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id
            productRequest.setMerId(merId);
            productRequest.setContent(excelVo.getStoreInfo());
            productRequest.setKeyword(excelVo.getKeyword());
            productRequest.setStoreInfo(excelVo.getStoreInfo());
            productRequest.setStoreName(excelVo.getStoreName());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(cost);
            productRequest.setOtPrice(otPrice);
            productRequest.setCost(cost);
            productRequest.setSourceCost(cost);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(tempId);
            //  供应商
            productRequest.setSuppliersId(supplierInfo.getSupplierId());
            productRequest.setSuppliersName(supplierInfo.getSupplierName());

            productRequest.setBarCode(barCode);
            productRequest.setCateId(excelVo.getCateId());
            productRequest.setCateIds(Collections.singletonList(excelVo.getCateId()));
            productRequest.setImage(mainImage);
            productRequest.setSliderImage(gallery.toJSONString());
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            //tod 1
            productRequest.setUnitName("件");
            productRequest.setComposition(excelVo.getComposition());
            productRequest.setDimension(excelVo.getDimension());
            productRequest.setColorCode(excelVo.getColorCode());
            productRequest.setSeasonCode(excelVo.getSeasonCode());
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
            productRequest.setWeight(excelVo.getWeight());
            if(excelVo.getWeight() == null){
                CategoryMatch supCategoryMatch = categoryMatchService.getById(excelVo.getCateId());
                productRequest.setWeight(supCategoryMatch.getWeight());
            }
            productRequest.setProductionPlace(excelVo.getProductionPlace());
            productRequest.setCountryId(systemCountryService.getIdByName(excelVo.getCountry()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return productRequest;
    }

}

